package com.dianrui.operation.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Process;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.dianrui.operation.Constant;
import com.dianrui.operation.MyApplication;
import com.dianrui.operation.R;
import com.dianrui.operation.fragment.MineFragment;
import com.dianrui.operation.fragment.OpetationFragment;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements AMapLocationListener {
    private static final String HOME_FRAGMENT_KEY = "opetationFragment";
    private static final String MNIE_FRAGMENT_KEY = "mineFragment";
    private List<Fragment> fragmentList = new ArrayList<>();
    private Timer timer;
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;


    @BindView(R.id.act_main_group_radioGroup)
    RadioGroup radioGroup;

    //首页
    @BindView(R.id.act_main_rl_radio_home)
    RelativeLayout rlRadioHome;
    @BindView(R.id.act_main_radio_home)
    RadioButton mainRadioHome;

    //我的
    @BindView(R.id.act_main_rl_radio_rl_radio_account)
    RelativeLayout rlRadioMy;
    @BindView(R.id.act_main_radio_account)
    RadioButton actMainRadioAccount;

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.top_right_imgs)
    ImageView topRightImg;



    private RadioButton[] buttonRadios;

    private int currentShowFragment;
    private int lastShowFragment = 0;

    private OpetationFragment opetationFragment;//我的运维

    private MineFragment mineFragment;//我的

    private long clicktime;
    private double currentLatitude;
    private double currentLongitude;
    private double lastlatitude;
    private double lastlongitude;



    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        title.setText(getString(R.string.app_name));
        topRightImg.setImageResource(R.mipmap.setting_img);
        topRightImg.setVisibility(View.GONE);
        back.setVisibility(View.GONE);
        buttonRadios = new RadioButton[]{mainRadioHome,
                actMainRadioAccount};
        changePage(0);
        loginAgain();
        if (!MyUtil.isGpsEnable(MainActivity.this)) {
            showOpenGpsDialog();
        }
        loadLocation();
        StartSendLat();
    }

    private void loginAgain() {
        JsonObject loginJson =new JsonObject();
        loginJson.addProperty("device_number",MyUtil.getUniqueId(MainActivity.this));
        StringBuilder loginAgainBulider=new StringBuilder();
        loginAgainBulider.append(SharedUtil.getUrl()).append(Url.AGAIN_LOGIN);
        XHttpRequest.getInstance().postRequests(loginAgainBulider.toString(), loginJson .toString(),  new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null!=jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                spUtils.put("account", jsonObject.optJSONObject("data").optString("account"));
                                spUtils.put("nickname", jsonObject.optJSONObject("data").optString("nickname"));
                                spUtils.put("mobile", jsonObject.optJSONObject("data").optString("mobile"));
                                spUtils.put("email", jsonObject.optJSONObject("data").optString("email"));
                                spUtils.put("alias", jsonObject.optJSONObject("data").optString("alias"));
                                spUtils.put("face", jsonObject.optJSONObject("data").optString("face"));
                                spUtils.put("scan_url", jsonObject.optJSONObject("data").optString("scan_url"));
                                MyApplication.initJiGuangUser(jsonObject.optJSONObject("data").optString("alias"), MainActivity.this);
                                spUtils.put("menu", String.valueOf(result));
                                SharedUtil.setToken(jsonObject.optJSONObject("data").optString("token"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpLoginActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    private void loadLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }
    }

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void StartSendLat() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(currentLatitude==0||currentLongitude==0){
                    return;
                }
                if(lastlatitude==0||lastlongitude==0){
                    //type 1
                    sendLatAndLng(currentLongitude,currentLatitude,"1");
                    lastlatitude=currentLatitude;
                    lastlongitude=currentLongitude;
                }else {
                    if(distanceover10()){
                        sendLatAndLng(currentLongitude,currentLatitude,"1");
                        lastlatitude=currentLatitude;
                        lastlongitude=currentLongitude;
                    }else {
                        sendLatAndLng(currentLongitude,currentLatitude,"0");
                    }
                }
            }
        };
        timer.schedule(task, 0, 10000);
    }

    private void sendLatAndLng(double lng,double lat,String isMove) {
        JsonObject jsonObject = new JsonObject();
        if (currentLatitude == 0.0 && currentLongitude == 0.0) {

        }else {
            jsonObject.addProperty("lng", currentLongitude);
            jsonObject.addProperty("lat", currentLatitude);
            jsonObject.addProperty("is_move", isMove);

        }
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.FOOTPRINT, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {

                            } else {

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    private boolean distanceover10(){
        double distance = AMapUtils.calculateLineDistance(new LatLng(lastlatitude, lastlongitude), new LatLng(currentLatitude, currentLongitude));
        if(distance>5){
            return true;
        }
        return false;
    }


    private void changePage(int position) {
        currentShowFragment = position;
        if (buttonRadios != null) {
            buttonRadios[lastShowFragment].setChecked(false);
        }

        if (buttonRadios != null) {
            for (int i = 0; i < buttonRadios.length; i++) {
                buttonRadios[i].setChecked(false);
            }
        }
        buttonRadios[position].setChecked(true);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        hideFragments(transaction);
        switch (position) {
            case 0:
                if (opetationFragment == null) {
                    opetationFragment = new OpetationFragment();
                    transaction.add(R.id.act_main_container, opetationFragment);
                } else {
                    transaction.show(opetationFragment);
                }
                break;

            case 1:
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    transaction.add(R.id.act_main_container, mineFragment);
                } else {
                    transaction.show(mineFragment);
                }
                break;

                default:
                    break;
        }
        transaction.commitAllowingStateLoss();
        lastShowFragment = position;
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (opetationFragment != null) {
            transaction.hide(opetationFragment);
        }

        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
    }

    @Override
    public void initData() {}

    @OnClick({R.id.act_main_radio_home, R.id.act_main_radio_account, R.id.top_right_imgs})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.act_main_radio_home:
                changePage(0);
                title.setText(getString(R.string.app_name));
                topRightImg.setImageResource(R.mipmap.setting_img);
                topRightImg.setVisibility(View.GONE);
                break;
            case R.id.act_main_radio_account:
                changePage(1);
                title.setText(getString(R.string.my_title));
                topRightImg.setImageResource(R.mipmap.setting_img);
                topRightImg.setVisibility(View.VISIBLE);
                break;
            case R.id.top_right_imgs:
                JumpActivitys(SettingsActvity.class);
                break;

                default:
                    break;

        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - clicktime < 3000) {
                this.finish();
                MyUtil.getInstance().clear();
                Process.killProcess(Process.myPid());
                System.exit(0);
                if (null != mLocationClient) {
                    mLocationClient.onDestroy();
                    mLocationClient.stopLocation();
                    mLocationClient = null;
                }
                if (timer!= null) {
                    timer.purge();
                    timer.cancel();
                }
            } else {
                ToastUtil.showToast(getString(R.string.press_exit));
                clicktime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showOpenGpsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.activity_dialog);
        final View view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.open_gps_dialog, null);
        final AlertDialog pausedialog = builder.create();
        pausedialog.setView(view2);
        pausedialog.setCanceledOnTouchOutside(false);
        pausedialog.show();
        final Button yes = view2.findViewById(R.id.yes);

        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pausedialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            currentLatitude = aMapLocation.getLatitude();
            currentLongitude = aMapLocation.getLongitude();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
            mLocationClient.stopLocation();
            mLocationClient = null;
        }
        if (timer!= null) {
            timer.purge();
            timer.cancel();
        }
    }
}
